/**
 * @description: 背景音乐播放组件
 * @update: 2019-08-13
 * @version: 1.1
 **/

(function(win) {
    /**
     * {Object}  options
     * {Boolean} options.autoPlay    是否自动播放，默认false
     * {String}  options.url     音频播放地址，默认 http://i1.cy.com/kzgj/pic/2019/0514/bgm.mp3
     * {String}  options.iconStart   播放icon，默认 https://www.changyou.com/cdn/music/1.0.0/img/start.png
     * {String}  options.iconStop    停止icon，默认 https://www.changyou.com/cdn/music/1.0.0/img/stop.png
     * {Number}  options.size        icon大小，默认 50
     * {Object}  options.parent     绝对定位父元素，默认 $(body)
     * {Number}  options.left/top/right/bottom      相对父元素位置，默认：auto/20/20/auto
     */
    var MusicPlay = function(options) {
        var _options = {
            autoPlay: false,
            url: '',
            iconStart: 'https://www.changyou.com/cdn/music/1.0/img/start.png',
            iconStop: 'https://www.changyou.com/cdn/music/1.0/img/stop.png',
            parent: $('body'),
            size: 50,
            top: 20,
            right: 20,
            bottom: 'auto',
            left: 'auto'
        };
        this.options = $.extend(_options, options);
        if(!_options.url) return alert('请填写音乐路径');
        var that = this;
        // 设定父元素为相对定位
        _options.parent.css({postion: 'relation'});
        // 对icon图片预加载，使点击平滑过渡
        $('<img />').attr('src', _options.autoPlay ? _options.iconStop : _options.iconStart);

        var startClass = 'music_start';
        var stopClass = 'music_stop';
        var $btnM = $('<a href="javascript:;" class="music_btn ' + (_options.autoPlay ? startClass : stopClass) + '">').css({
            width: _options.size,
            height: _options.size,
            left: _options.left,
            right: _options.right,
            top: _options.top,
            bottom: _options.bottom,
            backgroundRepeat: 'no-repeat',
            backgroundPosition: 'center center',
            zIndex: 300
        }).appendTo(_options.parent);
        var $audio = $('<audio src=' + _options.url + ' class="bg_music" hidden preload="auto" loop>').appendTo($('body'));
        var audio = $audio[0];
        var window_init = true;

        function audioResult(flag) {
            _options.autoPlay = flag;
            if(flag) {
                $btnM.addClass(startClass).removeClass(stopClass)
                    .css({backgroundImage: 'url(' + _options.iconStart + ')'});
                audio.play();
                if(!audio.paused) {
                    window_init = false;
                }
            }else {
                $btnM.addClass(stopClass).removeClass(startClass)
                    .css({backgroundImage: 'url(' + _options.iconStop + ')'});
                audio.pause();
            }
        }
        this.audioResult = audioResult;
        $btnM.click(function(e) {
            audioResult(!_options.autoPlay);
        });

        function isMobile() {
            return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
        }

        if(_options.autoPlay) {
            if(isMobile()) {
                // 创建页面监听，等待微信端页面加载完毕 触发音频播放
                document.addEventListener('DOMContentLoaded', function () {
                    audioResult(true);
                    document.addEventListener("WeixinJSBridgeReady", function () {
                        audioResult(true);
                    }, false);
                });
                // 创建触摸监听，当浏览器打开页面时，触摸屏幕触发事件，进行音频播放
                $btnM.on('touchstart', function(e) {
                    e.stopPropagation();
                });
                document.addEventListener('touchstart', function () {
                    if(window_init) {
                        audioResult(true);
                    }
                });
            }else {
                audio.oncanplaythrough = function() {
                    audioResult(true);
                }
            }
        }else {
            audioResult();
        }
    };

    MusicPlay.fn = MusicPlay.prototype = {
        stop: function() {
            this.audioResult(false);
        },
        start: function() {
            this.audioResult(true);
        }
    };
    win.MusicPlay = MusicPlay;
})(window);

